<template>
  <Modal :style="{'top': '60px','min-height': '100px'}" 
  :closable="false" width="60%" :footer="null" 
  v-model:visible="show" title="导出EPUB文件管理">
    <div style='display: flex'>
      <!-- <div style="width: 70%">
        <Input v-model:value="audioSrc" placeholder="地址，e.g. https://xxx.mp3"></Input>
      </div> -->
      <div :style="{width: '100%',textAlign: 'right'}">
        <!-- <Button style="margin-left: 10px" type="primary" @click="itserntAudio()">插入</Button> -->
        <Button style="margin-left: 10px" type="primary" @click="upload()">上传</Button>
        <Button style="margin-left: 10px" @click="close()" >取消</Button>
         <input value="" ref="audioFile" type="file" accept="text/html" id="audioFile" style='display: none'
               @change="insertAudioElement">
      </div>
    </div>
    <div  class="list-box">
      <Spin :spinning='spinning'>
      </Spin>
      <Row v-if="!spinning && dataList && dataList.rows">
        <Col style="padding: 10px" :span="6" v-for="(item,index) in dataList.rows" :key="index">
          <Card hoverable style="width: 100%">
            <template #cover>
              <div class="item-box">
              <!-- <audio  :src="item.fileUrl.split('1/profile').join('2')" controls="controls">
                您的浏览器不支持 audio 标签。
              </audio> -->
              </div>
            </template>
            <CardMeta :title="item.fileName">
              <template #description>
                <!-- <Button size="small" style="margin-right: 10px">查看</Button> -->
                <!-- <Button size="small" type="primary" @click="selectAudioPath(item.fileUrl)">导出EPUB</Button> -->
                <Button size="small" type="primary" @click="openBookInfo(item)">导出EPUB</Button>
              </template>
            </CardMeta>
          </Card>
        </Col>
      </Row>
    </div>
    
    <Modal 
      :style="{'top': '60px','min-height': '100px'}" 
      width="60%"  
      v-model:visible="bookDioalog" 
      :footer="null"
      title="书籍信息配置"
    >
    <Form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <FormItem label="书籍名称" name="title">
         <Row>
          <Col :span="8"  style="text-align: right">  
            <span>书籍名称：</span>
          </Col>
          <Col :span="12">        
            <Input v-model:value="formState.title" />
          </Col>
        </Row>
      </FormItem>
      <FormItem label="作者名称" name="author">
        <Row style="margin-top: 10px">
          <Col :span="8" style="text-align: right">  
            <span>作者名称：</span>
          </Col>
          <Col :span="12">        
            <Input v-model:value="formState.author" />
          </Col>
        </Row>
      </FormItem>
      <FormItem :wrapper-col="{ span: 14, offset: 4 }" style="text-align: center">
        <Button type="primary" @click="submitBookInfo">提交</Button>
        <Button style="margin-left: 10px" @click="bookDioalog=false">取消</Button>
      </FormItem>
    </Form>
    </Modal>
  </Modal>
</template>

<script lang="ts">
import {defineComponent, reactive, ref, onMounted} from 'vue'
import {message} from 'ant-design-vue'
import request from '@/utils/request'
// import { MessageSearch } from '@icon-park/vue-next'

export default defineComponent({
  name: 'audio-input',
  emits: ['insert', 'close'],
  props:["show"],

  setup(props, {emit}) {

    const audioSrc = ref('https://kankan.fun/assets/vue/music/mp3/daojiangxing.m4a')
    const audioFile = ref()
    let dataList = ref()
    const visible = ref(false)
    const spinning = ref(false)
    const bookDioalog = ref(false)
    const bookInfo = ref()
    const formRef = ref();
    const formState = reactive({
      title: undefined,
      author: undefined,
    })

    const rules = {
      title: {required: true, message: '书名',},
      author: {required: true, message: '作者',},
    };

    const resetForm = () => {
      formRef.value.resetFields();
    };

    const intsertAudio = () => {
      if (!audioSrc.value) return message.error('请先输入正确的音频地址')
      emit('insert', audioSrc.value)
    }
    
    const selectAudio = () => {
      visible.value = true
      spinning.value = true 
      getFileList()
    }

    const getFileList = () => {
      const query = {
        fileType: 'html'
      }
      request({
        url: '/systems/file/list',
        method: 'get',
        params: query
      }).then(res => {
        dataList.value = res
        spinning.value = false 
      }).catch(err => {
        message.error("数据加载失败")
        spinning.value = false
      })
    }

    const selectAudioPath = (val: string) =>{
      const path = val.split('1/profile').join('2');
      emit('insert', path)
    }
    const insertAudioElement = (e: any) => {
      const file = e.target.files[0]
      const params = new FormData()
      params.append('file',file)
      params.append('type','html')
      params.append('name',file.name.split('.')[0])
      uploadFile(params)
    }
    const uploadFile = (data: any) =>{
      spinning.value = true 
      request({
        url: '/systems/file/add',
        method: 'post',
        data: data
      }).then(res => {
        message.success("文件上传成功")
        spinning.value = false 
        getFileList()
      }).catch(err => {
        message.error("文件上传失败")
        spinning.value = false
      })
    }

    const close = () => emit('close')
    const upload = () => {
      const obj = document.getElementById('audioFile')
      if (obj) {
        obj.click()
      }
    }
    const openBookInfo = (item: any) => {
      bookInfo.value = item
      bookDioalog.value = true
    }
    const submitBookInfo = () => {
      formRef.value
        .validate()
        .then(() => {
          spinning.value = true 
          const data ={
            path: bookInfo.value.fileUrl.split('upload')[1],
            name: bookInfo.value.fileName,
            title: formState.title,
            author: formState.author,
          }
            request({
              url: '/systems/file/epub',
              method: 'post',
              data: data
            }).then((res: any) => {
              if(res.code === 200){
                bookDioalog.value = false
                spinning.value = false 
                message.success(res.msg)
                window.open('http://47.101.223.90:8382/upload'+res.data.path)
              }
            }).catch(err => {
              message.error("文件导出失败")
              spinning.value = false 
            })
        })
        .catch((error: any) => {
          spinning.value = false 
        });
    }

    onMounted(() => {
      getFileList()
    })
    
    return {
      formRef,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      formState,
      rules,
      audioSrc,
      intsertAudio,
      audioFile,
      visible,
      spinning,
      dataList,
      close,
      submitBookInfo,
      openBookInfo,
      bookDioalog,
      bookInfo,
      selectAudio,
      getFileList,
      upload,
      selectAudioPath,
      uploadFile,
      insertAudioElement
    }
  },
})
</script>

<style lang="scss">
.list-box {
  height: 500px;
  overflow: auto;
}

.item-box {
  audio {
    width: 100%;
    height: 100px;
  }
}

.audio-input {
  width: 480px;
}
.ant-modal-wrap {
  z-index: 2000;
}

.btns {
  margin-top: 10px;
  text-align: right;
}
</style>
